
package com.jf.cloud.supplier.controller.platform;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.auth.dto.AuthAccountDTO;
import com.jf.cloud.api.auth.feign.AccountFeignClient;
import com.jf.cloud.api.auth.vo.AuthAccountVO;
import com.jf.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.jf.cloud.api.supplier.constant.SupplierStatus;
import com.jf.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.supplier.constant.IsPreferred;
import com.jf.cloud.supplier.dto.SupplierAccountDTO;
import com.jf.cloud.supplier.dto.SupplierCreateInfoDTO;
import com.jf.cloud.supplier.dto.SupplierDetailDTO;
import com.jf.cloud.supplier.dto.SupplierSigningInfoDTO;
import com.jf.cloud.supplier.service.SupplierDetailService;
import com.jf.cloud.supplier.vo.SupplierDetailVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 供应商详情
 *
 * @author zz
 * @date 2020-12-05 15:50:25
 */
@RestController("platformSupplierDetailController")
@RequestMapping("/p/supplier_detail")
@Tag(name = "platform-供应商信息")
public class SupplierDetailController {

    @Value("${jfcloud.expose.permission:}")
    private Boolean permission;

    @Autowired
    private SupplierDetailService supplierDetailService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private AccountFeignClient accountFeignClient;

    @GetMapping("/page")
    @Operation(summary = "分页查询" , description = "分页查询")
    public ServerResponseEntity<PageVO<SupplierApiDetailVO>> getSupplierAuditingPage(PageDTO pageDTO, @ParameterObject SupplierDetailDTO supplierDetailDTO) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        return ServerResponseEntity.success(supplierDetailService.page(pageDTO, supplierDetailDTO));
    }

    @GetMapping("/info")
    @Operation(summary = "获取供应商基本信息" , description = "获取供应商基本信息")
    public ServerResponseEntity<SupplierApiDetailVO> getInfo(@RequestParam Long supplierId) {
        SupplierApiDetailVO supplierApiDetailVO = supplierDetailService.getBySupplierId(supplierId);
        if (BooleanUtil.isFalse(permission)){
            supplierApiDetailVO.setContactPhone(PhoneUtil.hideBetween(supplierApiDetailVO.getContactPhone()).toString());
        }
        ServerResponseEntity<AuthAccountVO> responseEntity = accountFeignClient.getAccountInfoByTenantId(supplierId, SysTypeEnum.SUPPLIER.value());
        if (responseEntity.isSuccess() && Objects.nonNull(responseEntity.getData())) {
            AuthAccountVO authAccountVO = responseEntity.getData();
            if (BooleanUtil.isFalse(permission)){
                supplierApiDetailVO.setSupplierAccount(PhoneUtil.hideBetween(authAccountVO.getPhone()).toString());
            } else {
                supplierApiDetailVO.setSupplierAccount(authAccountVO.getPhone());
            }
            supplierApiDetailVO.setAccountStatus(authAccountVO.getStatus());
        }
        return ServerResponseEntity.success(supplierApiDetailVO);
    }

    /**
     * 新建供应商
     */
    @PostMapping("/create_supplier")
    @Operation(summary = "新建供应商" , description = "新建供应商")
    public ServerResponseEntity<Void> createSupplier(@RequestBody SupplierCreateInfoDTO supplierCreateInfoDTO) {
        supplierDetailService.platformCreateSupplier(supplierCreateInfoDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "编辑供应商基本信息" , description = "编辑供应商基本信息")
    public ServerResponseEntity<Void> editSupplier(@RequestBody SupplierDetailDTO supplierDetailDTO) {
        if (Objects.isNull(supplierDetailDTO.getSupplierId())) {
            throw new LuckException("供应商id不能为空");
        }
        supplierDetailService.update(supplierDetailDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_signing_info")
    @Operation(summary = "更新供应商签约信息" , description = "更新供应商签约信息")
    public ServerResponseEntity<Void> updateSigningInfo(@RequestBody @Valid SupplierSigningInfoDTO supplierSigningInfoDTO) {
        if (Objects.isNull(supplierSigningInfoDTO.getSupplierId())) {
            throw new LuckException("供应商id不能为空");
        }
        supplierDetailService.updateSigningInfo(supplierSigningInfoDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_supplier_preferred")
    @Operation(summary = "当前供应商为优选，则取消优选;不是优选，则设置为优选" , description = "当前供应商为优选，则取消优选;不是优选，则设置为优选")
    public ServerResponseEntity<Void> updateSupplierPreferred(@RequestParam(value = "supplierId", required = true) Long supplierId) {
        SupplierApiDetailVO supplierApiDetailVO = supplierDetailService.getBySupplierId(supplierId);
        supplierApiDetailVO.setIsPreferred(Objects.equals(supplierApiDetailVO.getIsPreferred(), IsPreferred.YES.value()) ? IsPreferred.NO.value() : IsPreferred.YES.value());
        supplierDetailService.update(mapperFacade.map(supplierApiDetailVO, SupplierDetailDTO.class));
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_password")
    @Operation(summary = "更新供应商账户的登录密码" , description = "更新供应商账户的登录密码")
    public ServerResponseEntity<Void> updatePassword(@RequestBody SupplierAccountDTO supplierAccountDTO) {
        if (Objects.equals(supplierAccountDTO.getSupplierId(), Constant.ON_LINE_SUPPLIER_ID) && BooleanUtil.isFalse(permission)) {
            throw new LuckException("没有权限进行操作");
        }
        ServerResponseEntity<AuthAccountVO> merchantInfoByTenantId = accountFeignClient.getAccountInfoByTenantId(supplierAccountDTO.getSupplierId(), SysTypeEnum.SUPPLIER.value());
        if (!merchantInfoByTenantId.isSuccess()) {
            throw new LuckException("服务异常");
        }
        AuthAccountVO authAccountVO = merchantInfoByTenantId.getData();
        authAccountVO.setPassword(supplierAccountDTO.getPassword());
        accountFeignClient.update(mapperFacade.map(authAccountVO, AuthAccountDTO.class));
        return ServerResponseEntity.success();
    }

    @PutMapping("/offline")
    @Operation(summary = "下线供应商" , description = "下线供应商")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        Long sysUserId = AuthUserContext.get().getUserId();
        SupplierApiDetailVO supplierApiDetailVO = supplierDetailService.getBySupplierId(offlineHandleEventDTO.getHandleId());
        if (Objects.isNull(supplierApiDetailVO)) {
            throw new LuckException("未找到该供应商信息");
        }
        if (!Objects.equals(supplierApiDetailVO.getSupplierStatus(), SupplierStatus.OPEN.value()) && !Objects.equals(supplierApiDetailVO.getSupplierStatus(), SupplierStatus.STOP.value())) {
            throw new LuckException("供应商不处于营业或者停业状态,不能进行下线");
        }
        supplierDetailService.offline(supplierApiDetailVO, offlineHandleEventDTO.getOfflineReason(), sysUserId);


        return ServerResponseEntity.success();
    }

    @GetMapping("/count_by_supplier_status")
    @Operation(summary = "根据供应商状态查询供应商数量" , description = "根据供应商状态查询供应商数量")
    public ServerResponseEntity<Long> countBySupplierStatus(@RequestParam(value = "supplierStatus", required = false, defaultValue = "3") Long supplierStatus) {
        Long countBySupplierStatus = supplierDetailService.countBySupplierStatus(supplierStatus);
        return ServerResponseEntity.success(countBySupplierStatus);
    }

    @PostMapping("/online_audit")
    @Operation(summary = "供应商违规下线，重新申请上线审核" , description = "供应商违规下线，重新申请上线审核")
    public ServerResponseEntity<Void> onlineAudit(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        supplierDetailService.onlineAudit(offlineHandleEventDTO);
        return ServerResponseEntity.success();
    }

    @GetMapping("/page_supplier")
    @Operation(summary = "供应商列表" , description = "供应商列表")
    public ServerResponseEntity<PageVO<SupplierDetailVO>> pageSupplier(@Valid PageDTO pageDTO, @ParameterObject SupplierDetailDTO supplierDetailDTO) {
        supplierDetailDTO.setSysType(SysTypeEnum.PLATFORM.value());
        return ServerResponseEntity.success(supplierDetailService.pageSupplier(pageDTO,supplierDetailDTO,null));
    }

}
